#include "zk_node_endpoint.h"

#include <boost/lexical_cast.hpp>

#include "base/property_util.h"
#include "base/logging.h"

namespace melon {
namespace client {

ZkNodeEndpoint::ZkNodeEndpoint(const std::string & path, base::ZookeeperClient * zk_client) 
    : path_(path)
    , enabled_(false)
    , healthy_(true)
    , zk_client_(zk_client) {
  size_t pos = path.find_last_of('/');
  addr_ = path.substr(pos + 1);
  pos = addr_.find(':');
  host_ = addr_.substr(0, pos);
  try {
    port_ = boost::lexical_cast<int>(addr_.substr(pos + 1));
  } catch (...) {
    LOG_WARN("ZkNodeEndpoint " << path_ << " bad path"); 
  }
}

ZkNodeEndpoint::~ZkNodeEndpoint() {
}

bool ZkNodeEndpoint::PropIsEnabled(const std::map<std::string, std::string> & props) {
  std::map<std::string, std::string>::const_iterator it = props.find("status");
  if (it != props.end() && (it->second == "enabled")) {
    return true;
  }
  return false;
}

bool ZkNodeEndpoint::PropIsHealthy(const std::map<std::string, std::string> & props) {
  std::map<std::string, std::string>::const_iterator it = props.find("healthy");
  if (it != props.end() && (it->second == "0")) {
    return false;
  }
  return true;
}

bool ZkNodeEndpoint::Load() {
  std::string data;
  if (zk_client_->GetValue(path_.c_str(), &data) != 0) {
    LOG_WARN("ZkNodeEndpoint " << path_ << " load err"); 
    // 加载失败时，保持现有状态不变
    return false;
  }

  std::map<std::string, std::string> props;
  base::ParseProperty(data, &props);
  enabled_ = PropIsEnabled(props);
  healthy_ = PropIsHealthy(props);

  LOG_INFO("ZkNodeEndpoint " << path_ << " : enabled=" 
    << enabled_ << " healthy=" << healthy_);
  // zk_client_->AddNodeListener(path_.c_str(), shared_from_this());
  return true;
}

}
}

